# 实战篇 3:天气页面样式布局开发
# 先写一个 icon 组件
「新鲜天气」项目中,用到的 icon 比较多,比如天气图标、心情签到的表情,都是来自 icon 组件,本小节介绍下如何自定义个 icon 组件。
我们项目的自定义组件放在 client/components 目录下,首先在其目录下创建 icon 目录,创建组件的页面、样式和 JS 文件:
client/components
└── icon
├── index.js
├── index.json
├── index.scss
├── index.wxml
└── weather.ttf
@前端进阶之旅: 代码已经复制到剪贴板
组件需要在自己的页面配置文件(page.json,即 index.json)中声明自己是一个组件:
// index.json
{
"component": true
}
@前端进阶之旅: 代码已经复制到剪贴板
# 编写组件代码
icon 组件的 WXML 部分代码很简单:
<!--index.wxml-->
<text class="icon icon-{{ type }}"></text>
@前端进阶之旅: 代码已经复制到剪贴板
笔者定义了一个 icon 的类型字段,该字段由使用方传入,所以对应 JS 的写法为:
// index.js
Component({
properties: {
type: {
type: String,
value: ''
}
}
});
@前端进阶之旅: 代码已经复制到剪贴板
JS 中使用了 Component 构造器,调用 Component 构造器时可以指定组件的属性、数据、方法等。上面代码中定义了组件可以接受的 properties 有 type,type 是一个字符串类型的值,默认值是空字符串。
跟所有的 icon 样式写法一样,笔者通过图标共有的 class icon 定义了统一的样式,包括字体、大小等:
/* index.scss */
@font-face {
font-family: "weather";
src: url("./weather.ttf") format("truetype");
}
.icon {
font-style: normal;
-webkit-font-smoothing: antialiased;
-webkit-text-stroke-width: .4rpx;
-moz-osx-font-smoothing: grayscale;
}
.icon::after,
.icon::before {
font-family: weather !important;
}
@前端进阶之旅: 代码已经复制到剪贴板
然后通过 .icon-{{type}} 定义了不同的图标对应 class 的 content:
/* index.scss */
.icon.icon-xiaolian:before {
content: "\e60f";
}
.icon.icon-shidu:before {
content: "\e610";
}
.icon.icon-zhongyu:before {
content: "\e611&qu